package com.chenshuang.web;

import com.chenshuang.bean.Admin;
import com.chenshuang.service.AdminServise;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name = "LoginServlet", value = "/Login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 编码设置
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //从浏览器获取账号密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");


        AdminServise adminServise = new AdminServise();

        Admin admin =  adminServise.query(username,password);
        HttpSession session = request.getSession();

        if (admin!=null){
            // 查询不为空 成功


                    //  获取当前的时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日_HH时mm分ss秒");
            String format = sdf.format(new Date());
            System.out.println(format);
                    // 存到 cookie 中
            Cookie time = new Cookie(username,format);
            response.addCookie(time);
            Cookie[] cookies = request.getCookies();

            // 返回提示字符串信息，存到共享域
            String tips = adminServise.isfirst(username, cookies);
            session.setAttribute("tips",tips);

            session.setAttribute("username",admin);//在共享域中存入用户信息
            request.getRequestDispatcher("WEB-INF/index.jsp").forward(request,response);
        }else {
            // 失败
            session.setAttribute("m1","用户和密码不正确哦");
            session.setAttribute("m2","请重新登录！");

            request.getRequestDispatcher("relogin.jsp").forward(request,response);
        }

    }
}
